import { getUserInfo, oauth2, openIdCode } from '@/api/auth'
import store from './store'
import { SET_USER_OPEN_ID, SET_USER_INFO, SET_TOKEN } from '@/store/types'
import { getUrlParams } from './utils/common'
import { TOKEN, TOKEN_EXPIRATIONTIME } from '@/utils/storageTypes'

// #ifdef H5
async function h5Auth() {
  const query = getUrlParams(location.href)
  let oauth: AnyObject = {}
  if (query.search.code || query.hash.code) {
    oauth = await getUserInfo({
      code:query.search.code || query.hash.code,
      redirect_uri:
        window.location.origin +
        window.location.pathname +
        window.location.hash,
    })
    console.log('oauth',oauth)
    if(oauth && oauth.code == 200 && oauth.data.token){
      uni.setStorageSync(TOKEN, oauth.data.token)
      store.commit(`user/${SET_TOKEN}`,oauth.data.token)
      uni.setStorageSync(TOKEN_EXPIRATIONTIME,oauth.data.expirationTime)
      uni.setStorageSync('openId', oauth.data.openId)
      store.commit(`user/${SET_USER_OPEN_ID}`, oauth.data.openId)
      uni.setStorageSync('userInfo', oauth.data)
      store.commit(`user/${SET_USER_INFO}`, oauth.data)
    }
  } else {
    oauth = await oauth2({
      redirect_uri:
        window.location.origin +
        window.location.pathname +
        window.location.hash,
    })
  }
  return oauth
}

h5Auth()

// #endif

// #ifdef MP-WEIXIN
async function getOpenid() {
  uni.login({
    success(res) {
      openIdCode({ code: res.code }).then((_res) => {
        uni.setStorageSync('openId', _res.data.openId)
        store.commit(`user/${SET_USER_OPEN_ID}`, _res.data.openId)
      })
    },
    fail(err: GeneralCallbackResult) {
      console.log(err)
    },
  })
}
getOpenid()
// #endif
